package controllers;

import java.util.LinkedList;
import java.util.List;

import play.db.jpa.JPA;
import play.mvc.Controller;

import model.Player;
import model.Room;

public class RoomRegistry extends Controller {
	private List<Room> activeRooms;
	private Thread removeActiveRooms;
	static private RoomRegistry instance;
	
	private RoomRegistry() {
		activeRooms = new LinkedList<Room>();
		removeActiveRooms = new RemoveRoomsThread(activeRooms);
		removeActiveRooms.start();
	}

	static public RoomRegistry getInstance() {
		if (instance==null) instance = new RoomRegistry();
		return instance;
	}
	
	public Room newRoom(Player requester, String name, String passwd) {
		Room r = new Room(name, passwd);
		r.addPlayer(requester);
		if (r.save()) {
			return r;
		}
		else return null; 
	}
	
	public Room playerJoinRoom(Player requester, Room room, String passwd) {
		if (room.getPasswd().compareTo(passwd)==0) {
			room.addPlayer(requester);
			if (room.save()) {
				return room;
			}
			else return null;
		}
		else return null;
	}
	
	public Room leaveRoom(Player requester, Room room, boolean timeout) {
		room.removePlayer(requester);
		if (room.save()) {
			return room;
		} else return null;
	}
	
	public Room findRoom(String name) { 
		return JPA.em().find(Room.class, name); 
	}
	
	private class RemoveRoomsThread extends Thread {
		private List<Room> monitoring;
		public RemoveRoomsThread(List<Room> activeRooms) {
			monitoring = activeRooms;
		}

		@Override
		public void run() {
			for (Room r : monitoring) {
				if (r.hasPlayers()) {
					monitoring.remove(r);
				}
			}
		}
	}

	protected List<Room> getRooms() {
		return activeRooms;
	}
}
